<template>
  <div class="password-change p-6">
    <div class="mb-6">
      <h2 class="text-xl font-semibold text-gray-800">修改密码</h2>
      <p class="text-gray-500 text-sm mt-1">定期更换密码可以提高账号安全性</p>
    </div>

    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-position="top"
      class="max-w-lg"
    >
      <!-- Current Password -->
      <el-form-item label="当前密码" prop="currentPassword">
        <el-input
          v-model="form.currentPassword"
          type="password"
          placeholder="请输入当前密码"
          show-password
        >
          <template #prefix>
            <el-icon><Lock /></el-icon>
          </template>
        </el-input>
      </el-form-item>

      <!-- New Password -->
      <el-form-item label="新密码" prop="newPassword">
        <el-input
          v-model="form.newPassword"
          type="password"
          placeholder="请输入新密码"
          show-password
          @input="validatePasswordStrength"
        >
          <template #prefix>
            <el-icon><Key /></el-icon>
          </template>
        </el-input>
        
        <!-- Password Strength Indicator -->
        <div class="mt-2">
          <div class="text-xs text-gray-500 mb-1">密码强度</div>
          <!-- <div class="flex gap-2">
            <div 
              v-for="(strength, index) in strengthLevels" 
              :key="index"
              class="h-1 flex-1 rounded transition-all duration-300"
              :class="[
                passwordStrength >= index + 1 ? strengthColors[index] : 'bg-gray-200'
              ]"
            ></div>
          </div> -->
          <div class="text-xs mt-1" :class="strengthTextColor">
            {{ strengthText }}
          </div>
        </div>

        <!-- Password Requirements -->
        <div class="mt-4 bg-gray-50 p-4 rounded-lg">
          <div class="text-sm text-gray-600 mb-2">密码要求：</div>
          <div class="grid grid-cols-2 gap-2">
            <div 
              v-for="(req, index) in passwordRequirements" 
              :key="index"
              class="flex items-center text-sm"
              :class="req.met ? 'text-green-600' : 'text-gray-500'"
            >
              <el-icon class="mr-1">
                <Check v-if="req.met" />
                <Close v-else />
              </el-icon>
              {{ req.text }}
            </div>
          </div>
        </div>
      </el-form-item>

      <!-- Confirm Password -->
      <el-form-item label="确认新密码" prop="confirmPassword">
        <el-input
          v-model="form.confirmPassword"
          type="password"
          placeholder="请再次输入新密码"
          show-password
        >
          <template #prefix>
            <el-icon><Key /></el-icon>
          </template>
        </el-input>
      </el-form-item>

      <!-- Submit Button -->
      <el-form-item>
        <div class="flex items-center gap-4">
          <el-button 
            type="primary" 
            @click="handleSubmit" 
            :loading="isSubmitting"
            :disabled="!isFormValid"
          >
            确认修改
          </el-button>
          <el-button @click="resetForm">重置</el-button>
        </div>
      </el-form-item>
    </el-form>

    <!-- Security Tips -->
    <div class="mt-8 bg-blue-50 border-l-4 border-blue-400 p-4">
      <div class="flex">
        <div class="flex-shrink-0">
          <el-icon class="text-blue-400"><InfoFilled /></el-icon>
        </div>
        <div class="ml-3">
          <h3 class="text-sm font-medium text-blue-800">安全提示</h3>
          <div class="mt-2 text-sm text-blue-700">
            <ul class="list-disc list-inside space-y-1">
              <li>建议使用字母、数字和符号的组合</li>
              <li>密码长度建议在12位以上</li>
              <li>请勿使用易被猜测的密码，如生日、手机号等</li>
              <li>请定期更换密码，提高账号安全性</li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { Lock, Key, Check, Close, InfoFilled } from '@element-plus/icons-vue'
import { updatePasswordWithoutCode } from '@/api/modules/user'
const formRef = ref<FormInstance>()
const isSubmitting = ref(false)

const form = ref({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// Password validation rules
const validatePass = (rule: any, value: string, callback: Function) => {
  console.log(rule, value, callback)
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    if (form.value.confirmPassword !== '') {
      if (formRef.value) {
        formRef.value.validateField('confirmPassword')
      }
    }
    callback()
  }
}

const validatePass2 = (rule: any, value: string, callback: Function) => {
  console.log(rule, value, callback)
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== form.value.newPassword) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

const rules: FormRules = {
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { validator: validatePass, trigger: 'blur' },
    { min: 8, message: '密码长度不能小于8位', trigger: 'blur' }
  ],
  confirmPassword: [
    { validator: validatePass2, trigger: 'blur' }
  ]
}

// Password strength checker
const passwordStrength = ref(0)

const strengthText = computed(() => {
  switch (passwordStrength.value) {
    case 0: return '非常弱'
    case 1: return '弱'
    case 2: return '中等'
    case 3: return '强'
    case 4: return '非常强'
    default: return ''
  }
})

const strengthTextColor = computed(() => {
  switch (passwordStrength.value) {
    case 0:
    case 1: return 'text-red-500'
    case 2: return 'text-orange-500'
    case 3: return 'text-yellow-500'
    case 4: return 'text-green-500'
    default: return ''
  }
})

// Password requirements
const passwordRequirements = ref([
  { text: '至少8个字符', met: false },
  { text: '包含大写字母', met: false },
  { text: '包含小写字母', met: false },
  { text: '包含数字', met: false },
  { text: '包含特殊字符', met: false },
  { text: '不能与当前密码相同', met: false }
])

function validatePasswordStrength() {
  const password = form.value.newPassword
  let strength = 0

  // Update requirements
  passwordRequirements.value[0].met = password.length >= 8
  passwordRequirements.value[1].met = /[A-Z]/.test(password)
  passwordRequirements.value[2].met = /[a-z]/.test(password)
  passwordRequirements.value[3].met = /[0-9]/.test(password)
  passwordRequirements.value[4].met = /[!@#$%^&*(),.?":{}|<>]/.test(password)
  passwordRequirements.value[5].met = password !== form.value.currentPassword

  // Calculate strength
  if (password.length >= 8) strength++
  if (/[A-Z]/.test(password)) strength++
  if (/[0-9]/.test(password)) strength++
  if (/[!@#$%^&*(),.?":{}|<>]/.test(password)) strength++

  passwordStrength.value = strength
}

// Form validation status
const isFormValid = computed(() => {
  return form.value.currentPassword &&
         form.value.newPassword &&
         form.value.confirmPassword &&
         form.value.newPassword === form.value.confirmPassword &&
         passwordStrength.value >= 2
})

// Form submission
async function handleSubmit() {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    isSubmitting.value = true
    await updatePasswordWithoutCode({
      oldPassword: form.value.currentPassword,
      newPassword: form.value.newPassword
    })
    // TODO: Implement API call
    ElMessage.success('密码修改成功')
    resetForm()
  } catch (error) {
    console.error('Form validation failed:', error)
    ElMessage.error('密码修改失败:' + error)
  } finally {
    isSubmitting.value = false
  }
}

function resetForm() {
  if (!formRef.value) return
  formRef.value.resetFields()
  passwordStrength.value = 0
  passwordRequirements.value.forEach(req => req.met = false)
}
</script>

<style scoped>
:deep(.el-form-item__label) {
  @apply text-gray-600 font-medium;
}

:deep(.el-input__wrapper) {
  @apply shadow-sm;
}

:deep(.el-input__wrapper:hover) {
  @apply shadow;
}

.strength-bar {
  @apply h-1 flex-1 rounded transition-all duration-300;
}
</style> 